<?php

class EarnedRevenueReportController extends Controller {

    public function actionIndex() {


        if (isset($_GET['form'])) {
            $startDateArr = explode('/', $_GET['form']['startdate']);
            $startdate = '';
            if (count($startDateArr) == 3) {
                $startdate = $startDateArr[2] . '-' . $startDateArr[0] . '-' . $startDateArr[1];
                if (isDateValid($startdate) == false) {
                    throw new CHttpException('Invalid start date');
                }
            } else {
                throw new CHttpException('Invalid start date');
            }
            $enddate = '';
            $endDateArr = explode('/', $_GET['form']['enddate']);
            if (count($endDateArr) == 3) {
                $enddate = $endDateArr[2] . '-' . $endDateArr[0] . '-' . $endDateArr[1];
                if (isDateValid($enddate) === false) {
                    throw new CHttpException('Invalid end date');
                }
            } else {
                throw new CHttpException('Invalid end date');
            }
            $inCondition = '';
            $inElenemts = array_keys($_GET['form']['ctype']);
            if (in_array('0', $inElenemts))
                $inElenemts = array_keys(ContractType::getListData());

            for ($index = 0; $index < count($inElenemts); $index++) {
                if ($index != count($inElenemts)) {
                    $inCondition.= $inElenemts[$index] . '",';
                } else
                    $inCondition.= $inElenemts[$index];
            }

            $invoiceData = Yii::app()->db->createCommand('
            SELECT c.*,l.*
            FROM tbl_contracts c
            INNER JOIN tbl_locations l ON l.locno = c.locno AND l.custno = c.custno
            
            AND c.contractstartdate BETWEEN :startdate AND :enddate     
            AND c.contractype in (:inCondition)
            group by c.contractid
            ORDER BY l.state
            ')->bindValues(array(
                        'startdate' => $startdate,
                        'enddate' => $enddate,
                        'inCondition' => $inCondition
                    ))->queryAll();
            if (count($invoiceData) == 0) {
                echo 'There are no data to show';
                exit;
            }
            foreach ($invoiceData as $i => $item) {

                $rs[$i] = $item;
                  $rs[$i]['invoiceList'] = Invoice::model()->findAll(
                        "agreementno =:agreementno and (invoicetype =:cm or invoicetype=:inv) ", array('agreementno' => $item['contractid'],
                    'cm' => Invoice::TYPE_CREDIT_MEMO,
                    'inv' => Invoice::TYPE_INVOICE
                        ));
               $rs[$i]['invamt'] = 0;
                $rs[$i]['tax'] = 0;
                $rs[$i]['taxRevenue'] = 0;
                foreach ($rs[$i]['invoiceList'] as $invoice) {
                   $rs[$i]['invamt'] += $invoice->amountcharge;
                    $rs[$i]['tax']+= $invoice->getTotalTax();
                }
                $this->calculateInvoiceEarnedRevenue($item, $rs[$i]);

                if (time() > strtotime($item['contractenddate']) || $rs[$i]['revenue'] == $rs[$i]['invamt']) {
                    $rs[$i]['isExpired'] = true;
                } else {
                    $rs[$i]['isExpired'] = false;
                }
              
            }


            $grandAmount = 0;
            $grandEarned = 0;
            $grandRevenueByMonths = array();
            $data = array();

            foreach ($rs as $i => $item) {
                $data[$item['state']]['items'][] = $item;
                if (!isset($data[$item['state']]['revenue'])) {
                    $data[$item['state']]['revenue'] = $item['revenue'];
                    
                } else {
                    $data[$item['state']]['revenue'] +=$item['revenue'];
                }
                if (!isset($data[$item['state']]['taxRevenue'])) {
                    $data[$item['state']]['taxRevenue'] = $item['taxRevenue'];
                    
                } else {
                    $data[$item['state']]['taxRevenue'] +=$item['taxRevenue'];
                }

                if (!isset($data[$item['state']]['amount'])) {
                    $data[$item['state']]['amount'] = $item['invamt'];
                } else {
                    $data[$item['state']]['amount']+=$item['invamt'];
                }
      
                for ($month = 1; $month <= 24; $month++) {
                    if (isset($item['revenueByMonths'])) {
                        $amount = $item['revenueByMonths'][$month];
                        if (!isset($data[$item['state']]['revenueByMonths'][$month])) {
                            $data[$item['state']]['revenueByMonths'][$month] = $amount;
                        } else {
                            $data[$item['state']]['revenueByMonths'][$month]+=$amount;
                        }
                        if (!isset($grandRevenueByMonths[$month])) {
                            $grandRevenueByMonths[$month] = $amount;
                        } else {
                            $grandRevenueByMonths[$month]+=$amount;
                        }
                    }
                }

                $grandAmount+=$item['invamt'];
                $grandEarned+=$item['revenue'];
            }

            $this->layout = '//layouts/space';
            $this->render('index', array(
                'data' => $data,
                'grandAmount' => $grandAmount,
                'grandRevenue' => $grandEarned,
                'grandRevenueByMonths' => $grandRevenueByMonths
            ));
        } else {
            $yearList = Yii::app()
                    ->db
                    ->createCommand('SELECT DISTINCT YEAR(  `contractstartdate` ) `contractYear` fROM  `tbl_contracts` order by `contractYear`')
                    ->queryAll();
            $this->render('earnedRevenueReportForm', array('yearList' => $yearList));
        }
    }

    protected function calculateInvoiceEarnedRevenue($item, &$data) {

        $startDate = new DateTime($item['contractstartdate']);
        $endDate = new DateTime($item['contractenddate']);
        $endDate->add(new DateInterval('P1D'));
        $curDate = new DateTime('now');
        $contractAmount = $data['invamt'];
        $taxRevenue = $data['taxRevenue'];
        $startMonth = $startDate->format('m');
        if ($item['contractype'] == Contracts::TYPE_MONTHLY || $item['contractype'] == Contracts::TYPE_QUARTERLY) {
            $contractMonthDiff = $startDate->diff($endDate, true);
            $monthPassDiff = $curDate->diff($startDate);
            $contractMonth = $contractMonthDiff->format('%y') * 12 + $contractMonthDiff->format('%m');
            $monthPass = $monthPassDiff->format('%y') * 12 + $monthPassDiff->format('%m');
        } else {
            $contractMonth = 12;
            $monthPassDiff = $curDate->diff($startDate);
            $monthPass = $monthPassDiff->format('%y') * 12 + $monthPassDiff->format('%m');
        }
        if (time() > strtotime($item['contractenddate'])) {

            $data['revenue'] = $contractAmount;
            $data['taxRevenue']=$taxRevenue;
        } else {
            //$amount = $contractAmount / $contractMonth * $monthPass;            
            $data['revenue'] = $contractAmount / $contractMonth * $monthPass;
            $data['taxRevenue']=$taxRevenue/ $contractMonth * $monthPass;
            }
        if ($contractMonth > 0) {

            $data['revenueByMonths'] = $this->getRevenueByMonth($contractAmount / $contractMonth, $startMonth, $monthPass, $contractMonth);
        }
    }

    protected function getRevenueByMonth($amountPerMonth, $startMonth, $monthPass, $contractMonth) {


        $rs = array();
        //$startMonth++;
        for ($i = 1; $i <= 24; $i++) {
            if ($i >= $startMonth && $i < $startMonth + $monthPass && $i < $contractMonth + $startMonth) {
                $rs[$i] = $amountPerMonth;
            } else {
                $rs[$i] = 0;
            }
        }

        return $rs;
    }

}